<template>
  <form-template
    class="form"
    v-model:form="form"
    :options="options"
    :loading="loading"
    @uploadOk="onUploadOk"
    @submit="onSubmit"
  ></form-template>
</template>

<script setup>
  import dayjs from 'dayjs'
  const router = useRouter()
  const route = useRoute()
  const loading = ref(false)
  const detailId = ref()
  const form = ref({})
  const options = ref([
    {label: '证照保管单位', key: 'custodyUnit', type: 'field', disabled: true},
    {label: '所属二级单位', key: 'secondaryUnit', type: 'field', disabled: true},
    {label: '持有人', key: 'holder', type: 'field', disabled: true},
    {label: '证照号码', key: 'certNumber', type: 'field', disabled: true},
    {
      label: '归还人单位',
      key: 'returnerUnit',
      type: 'picker',
      columns: [],
      filter: true,
      rules: [{required: true, message: '请选择归还人单位'}],
    },
    {
      label: '归还人',
      key: 'returner',
      type: 'picker',
      columns: [],
      filter: true,
      rules: [
        {
          validator: val => {
            const unit = form.value.returnerUnit
            const columns = options.value.find(item => item.key === 'returner')?.columns.length > 0
            return Boolean(unit && columns)
          },
          message: '请先选择归还人单位',
        },
        {required: true, message: '请选择归还人'},
      ],
    },
    {
      label: '归还日',
      key: 'returnTime',
      type: 'calendar',
      rules: [
        {
          validator: val => {
            return Boolean(dayjs(val, 'YYYY-MM-DD').isAfter(form.value.borrowingStartDate, 'YYYY-MM-DD'))
          },
          message: `归还日应在借用开始时间${form.value.borrowingStartDate?.split(' ')[0]}之后`,
        },
        {required: true, message: '请选择归还日'},
      ],
    },
    {label: '备注', key: 'returnRemark', type: 'textarea'},
    {label: '附件', key: 'attachmentUrl', type: 'upload', accept: ''},
  ])
  let fileList = []
  let unitColumns = []
  let userColumns = []
  watch(
    () => form.value.returnerUnitKeyWord,
    kw => {
      const returnerUnitItem = options.value.find(item => item.key === 'returnerUnit')
      if (kw?.length > 0) {
        returnerUnitItem.columns = unitColumns.filter(item => item.text.includes(kw))
      } else {
        returnerUnitItem.columns = unitColumns
      }
    }
  )
  watch(
    () => form.value.returnerKeyWord,
    kw => {
      const returnerItem = options.value.find(item => item.key === 'returner')
      if (kw?.length > 0) {
        returnerItem.columns = userColumns.filter(item => item.text.includes(kw))
      } else {
        returnerItem.columns = userColumns
      }
    }
  )
  watch(
    () => form.value.returnerUnit,
    val => {
      form.value.returner = undefined
      form.value.returnerValue = undefined
      const depId = form.value.returnerUnitValue
      $get('/bus/api/v1/department/user', {onlyUsers: true, hasSubordinate: true, depId: depId}).then(res => {
        const {data} = res
        const returnerItem = options.value.find(item => item.key === 'returner')
        const replaceData = data.map(item => {
          return {
            text: item.name,
            value: item.id,
          }
        })
        returnerItem.columns = replaceData
        userColumns = replaceData
      })
    }
  )
  const onUploadOk = list => {
    fileList = list
  }
  const onSubmit = () => {
    const params = {
      ...form.value,
      returnerUnitId: form.value.returnerUnitValue,
      returnerId: form.value.returnerValue,
      returnTime: form.value.returnTime + ' 00:00:00',
      attachmentUrl: fileList.attachmentUrl.map(item => item.url).join(','),
    }
    delete params.id
    delete params.createBy
    delete params.createTime
    delete params.updateBy
    delete params.updateTime
    delete params.deleted
    delete params.returnerUnitValue
    delete params.returnerUnitKeyWord
    delete params.returnerValue
    delete params.returnerKeyWord
    loading.value = true
    const loadingToast = showLoadingToast({
      duration: 500,
      message: '操作中...',
      forbidClick: true,
      loadingType: 'spinner',
    })
    $post('/api/v1/cert/borrow/record', params)
      .then(() => {
        showSuccessToast('归还成功')
        router.replace({path: '/'})
      })
      .finally(() => {
        loading.value = false
        loadingToast.close()
      })
  }
  const onLoad = id => {
    showLoadingToast({
      duration: 500,
      message: '加载中...',
      forbidClick: true,
      loadingType: 'spinner',
    })
    $get('/bus/api/v1/department/system/grade', {depType: 2}).then(res => {
      const {data} = res
      const returnerUnitItem = options.value.find(item => item.key === 'returnerUnit')
      const replaceData = data.map(item => {
        return {
          text: item.depName,
          value: item.depId,
          parent: item.parentId,
        }
      })
      returnerUnitItem.columns = replaceData
      unitColumns = replaceData
    })
    $get(`/api/v1/cert/borrow/record/${detailId.value}`)
      .then(res => {
        const {data} = res
        form.value = data
      })
      .finally(() => {
        closeToast()
      })
  }
  onMounted(() => {
    detailId.value = route.query?.id
    if (detailId.value) onLoad()
  })
</script>

<style scoped>
  .form {
    margin-top: 32px;
  }
</style>
